package com.zigong.app.ui.fragment;


import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.ArrayMap;
import android.util.Pair;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import com.canyinghao.canrefresh.CanRefreshLayout;
import com.jiongbull.jlog.JLog;
import com.ruihang.generalibrary.ui.dialog.BaseDialogFragment;
import com.ruihang.generalibrary.ui.util.OnItemInternalClick;
import com.ruihang.generalibrary.utils.DateUtils;
import com.ruihang.generalibrary.utils.GroupOrderHelper;
import com.ruihang.generalibrary.utils.ListUtils;
import com.ruihang.generalibrary.utils.NetModeUtil;
import com.ruihang.generalibrary.utils.ServerTime;
import com.ruihang.generalibrary.utils.SharedPreferencesUtil;
import com.zigong.app.R;
import com.zigong.app.application.Cache;
import com.zigong.app.base.BaseActivity;
import com.zigong.app.application.Constances;
import com.zigong.app.beans.FSubscribe;
import com.zigong.app.beans.FocusColumn;
import com.zigong.app.beans.LiveHomeAdvance;
import com.zigong.app.beans.LiveItem;
import com.zigong.app.beans.SingleResult;
import com.zigong.app.beans.Titles;
import com.zigong.app.http.AbsListNetCallback;
import com.zigong.app.http.AbsNetCallBack;
import com.zigong.app.http.NetUtils;
import com.zigong.app.ui.activities.MySubscribeActivity;
import com.zigong.app.ui.adapter.LiveHomeAdapter;
import com.zigong.app.ui.adapter.holder.LiveHomeItemHolder;
import com.zigong.app.ui.adapter.holder.OnlyTitleHolder;
import com.zigong.app.ui.adapter.holder.VideoPlayHolder;
import com.zigong.app.ui.dialog.NetModeDiaFragment;
import com.zigong.app.ui.util.IListShowData;
import com.zigong.app.ui.utils.LiveHomeDataAddHelper;
import com.zigong.app.ui.utils.LiveListGetHelper;
import com.zigong.app.ui.widget.BasePlayerView;
import com.zigong.app.utils.ListTypeUtils;

import java.sql.Date;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * 首页直播的界面
 */
public class LiveFragment extends ColumnBaseFragment implements CanRefreshLayout.OnRefreshListener, CanRefreshLayout.OnLoadMoreListener, LiveHomeItemHolder.LiveItemClickListener {

    @BindView(R.id.fm_live_refresh)
    protected CanRefreshLayout refreshLayout;
    @BindView(R.id.can_content_view)
    protected RecyclerView recyclerView;

    private LiveHomeDataAddHelper dataAddHelper;

    private LiveHomeAdapter adapter;

    private GroupOrderHelper groupOrderHelper;

    private List<IListShowData> advanceList = new ArrayList<>();

    /**
     * 直播的各栏目:直播,预约,回顾
     */
    private FocusColumn livingColumn, appiontColumn, reviewColumn;

    private LiveListGetHelper liveListGetHelper;
    private Handler handler;
    private int types = 1;
    private Calendar calendar;
    private int lastPlayIndex = 0;
    private int topPosition;
    private int bottomPosition;
    private LiveHomeItemHolder playHolder = null;
    private int playTemp = -1;
    private BasePlayerView playingPlayer;

    public LiveFragment() {
        // Required empty public constructor
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_live, container, false);
        ButterKnife.bind(this, view);
        return view;
    }

    private int recyclerViewBottom = 0;

    @Override
    protected void initViews(View v, @Nullable Bundle savedInstanceState) {
        handler = new Handler();
        groupOrderHelper = new GroupOrderHelper();
        dataAddHelper = new LiveHomeDataAddHelper();
        dataAddHelper.setFragment(this);
        refreshLayout.setOnLoadMoreListener(this);
        refreshLayout.setOnRefreshListener(this);
        recyclerView.setLayoutManager(new LinearLayoutManager(getContext(), LinearLayoutManager.VERTICAL, false));
        recyclerView.setItemAnimator(new DefaultItemAnimator());
        recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            boolean isUp = false;


            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                if (mShouldScroll && RecyclerView.SCROLL_STATE_IDLE == newState) {
                    mShouldScroll = false;
                    smoothMoveToPosition(recyclerView, mToPosition);
                }
                if (isNotScrollStateChanged) {
//                    isNotScrollStateChanged = false;
                    return;
                }
                if (recyclerView.getLayoutManager() != null && newState == 0) {//滑动停止
                    LinearLayoutManager layoutManager = (LinearLayoutManager) recyclerView.getLayoutManager();
                    topPosition = layoutManager.findFirstVisibleItemPosition();
                    bottomPosition = layoutManager.findLastVisibleItemPosition();
                    playTemp = -1;
                    final RecyclerView.LayoutManager manager = recyclerView.getLayoutManager();
                    View topView = layoutManager.findViewByPosition(topPosition);
                    if (null != topView) {
                        int bottom = topView.getBottom();
                        int height = topView.getHeight();
                        if (recyclerView.getChildViewHolder(topView) instanceof OnlyTitleHolder) {
                            topView = layoutManager.findViewByPosition(topPosition + 1);
                            bottom = topView.getBottom();
                            height = topView.getHeight();
                            if (bottom < height / 2) {
                                View view = manager.findViewByPosition(topPosition + 2);
                                if (null != view && recyclerView.getChildViewHolder(view) instanceof LiveHomeItemHolder) {
                                    playHolder = (LiveHomeItemHolder) recyclerView.getChildViewHolder(view);
                                    playTemp = topPosition + 1;
                                }

                            } else {
                                View view = manager.findViewByPosition(topPosition + 1);
                                if (null != view && recyclerView.getChildViewHolder(view) instanceof LiveHomeItemHolder) {
                                    playHolder = (LiveHomeItemHolder) recyclerView.getChildViewHolder(view);
                                    playTemp = topPosition + 1;
                                }
                            }
                        } else {
                            if (bottom < height / 2) {
                                View view = manager.findViewByPosition(topPosition + 1);
                                if (null != view && recyclerView.getChildViewHolder(view) instanceof LiveHomeItemHolder) {
                                    playHolder = (LiveHomeItemHolder) recyclerView.getChildViewHolder(view);
                                    playTemp = topPosition + 1;
                                }

                            } else {
                                View view = manager.findViewByPosition(topPosition);
                                if (null != view && recyclerView.getChildViewHolder(view) instanceof LiveHomeItemHolder) {
                                    playHolder = (LiveHomeItemHolder) recyclerView.getChildViewHolder(view);
                                    playTemp = topPosition;
                                }

                            }
                        }
                    }
                    if (playTemp != lastPlayIndex) {
                        if (null != playHolder) {
                            View lastView = manager.findViewByPosition(lastPlayIndex);
//                            if (null != lastView && recyclerView.getChildViewHolder(lastView) instanceof LiveHomeItemHolder) {
//                                LiveHomeItemHolder lastHolder = (LiveHomeItemHolder) recyclerView.getChildViewHolder(lastView);
//                                lastHolder.pauseVideo();
//                            }

//                            if (playTemp != -1 && playTemp < bottomPosition) {
//                                Handler handler = new Handler();
//                                handler.postDelayed(new Runnable() {
//                                    @Override
//                                    public void run() {
//                                        if (playTemp != -1 && playTemp < bottomPosition) {
//                                            playHolder.playVideo();
////                                            initPlayer(playHolder.getVideoPlayer());
//                                            lastPlayIndex = playTemp;
//                                        }
//                                    }
//                                }, 300);
//                            }
                        }
                    }
                }
            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                if (isNotScrolled) {
                    //点击视频时，不触发此处的处理逻辑
//                    isNotScrolled = false;
                    return;
                }
//                boolean isSignificantDelta = Math.abs(dy) > mScrollThreshold;
//                mScrollThreshold = Math.abs(dy);
//                if (dy > 0) {
//                    isUp = true;
//                } else {
//                    isUp = false;
//                }
                LinearLayoutManager layoutManager = (LinearLayoutManager) recyclerView.getLayoutManager();
                int topPosition = layoutManager.findFirstVisibleItemPosition();
                int bottomPosition = layoutManager.findLastVisibleItemPosition();
                int temp = -1;
                RecyclerView.LayoutManager manager = recyclerView.getLayoutManager();
//                View topView = layoutManager.findViewByPosition(topPosition);
//                if (null != topView) {
//                    if (recyclerView.getChildViewHolder(topView) instanceof LiveHomeItemHolder) {
//                        int bottom = topView.getBottom();
//                        int height = topView.getHeight();
//                        if (bottom < height / 2) {
//                            temp = topPosition + 1;
//                        } else {
//                            temp = topPosition;
//                        }
//                    }
//                }
//                if (temp != -1 && temp != lastPlayIndex || bottomPosition <= lastPlayIndex) {
//                    View lastView = manager.findViewByPosition(lastPlayIndex);
//                    if (null != lastView && recyclerView.getChildViewHolder(lastView) instanceof LiveHomeItemHolder) {
//                        LiveHomeItemHolder lastHolder = (LiveHomeItemHolder) recyclerView.getChildViewHolder(lastView);
//                        lastHolder.pauseVideo();
//                        lastPlayIndex = -1;
//                    }
//                }

                View playingView = layoutManager.findViewByPosition(lastPlayIndex);
                if (null != playingView) {
                    if (recyclerView.getChildViewHolder(playingView) instanceof LiveHomeItemHolder) {
                        recyclerViewBottom = recyclerView.getBottom();
                        int top = playingView.getTop();
                        int bottom = playingView.getBottom();
                        int height = playingView.getHeight();
                        boolean isShouldStop = false;
                        if (dy > 0) {
                            if (bottom < height / 2) {
                                isShouldStop = true;
                            }
                        } else {
                            if ((recyclerViewBottom - top) < height / 3) {
                                isShouldStop = true;
                            }
                        }
                        if (isShouldStop) {
                            LiveHomeItemHolder lastHolder = (LiveHomeItemHolder) recyclerView.getChildViewHolder(playingView);
                            lastHolder.pauseVideo();
                            lastPlayIndex = -1;
                        }
                    }
                }
            }

        });
    }

    private void intTop() {
        LinearLayoutManager layoutManager = (LinearLayoutManager) recyclerView.getLayoutManager();
        if (null != layoutManager) {
            topPosition = layoutManager.findFirstVisibleItemPosition();
            bottomPosition = layoutManager.findLastVisibleItemPosition();
        }
    }

    @Override
    protected void onFragmentUnShowed(boolean isCallFromPause) {
        super.onFragmentUnShowed(isCallFromPause);
        if (null != recyclerView) {
            intTop();
            pauseAll();
            RecyclerView.LayoutManager manager = recyclerView.getLayoutManager();
            View lastView = manager.findViewByPosition(lastPlayIndex);
            if (null != lastView && recyclerView.getChildViewHolder(lastView) instanceof LiveHomeItemHolder) {
                LiveHomeItemHolder lastHolder = (LiveHomeItemHolder) recyclerView.getChildViewHolder(lastView);
                lastHolder.pauseVideo();

            }
        }
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (hidden && null != recyclerView) {
            intTop();
            pauseAll();
            RecyclerView.LayoutManager manager = recyclerView.getLayoutManager();
            View lastView = manager.findViewByPosition(lastPlayIndex);
            if (null != lastView && recyclerView.getChildViewHolder(lastView) instanceof LiveHomeItemHolder) {
                LiveHomeItemHolder lastHolder = (LiveHomeItemHolder) recyclerView.getChildViewHolder(lastView);
                lastHolder.pauseVideo();

            }
        }
    }

    private void pauseAll() {
        for (int i = topPosition; i <= bottomPosition; i++) {
            if (null != recyclerView) {
                RecyclerView.LayoutManager manager = recyclerView.getLayoutManager();
                View lastView = manager.findViewByPosition(i);
                if (null != lastView && recyclerView.getChildViewHolder(lastView) instanceof LiveHomeItemHolder) {
                    LiveHomeItemHolder lastHolder = (LiveHomeItemHolder) recyclerView.getChildViewHolder(lastView);
                    lastHolder.pauseVideo();
                }
            }
        }
    }
//
//    /**
//     * 记录RecyclerView当前位置
//     */
//    private void showTheVideo(int lastIndex, int position) {
//        if (adapter.getItemViewType(position) != LiveHomeAdapter.VIEWTYPE_ADVANCE
//                && adapter.getItemViewType(position) != LiveHomeAdapter.VIEWTYPE_TITLE
//                && adapter.getItemViewType(position) != LiveHomeAdapter.VIEWTYPE_ADVANCE_LIST) {
//            RecyclerView.LayoutManager manager = recyclerView.getLayoutManager();
//            View view = manager.findViewByPosition(position);
//            if (null != view && recyclerView.getChildViewHolder(view) instanceof LiveHomeItemHolder && NetModeUtil.GetNetype(getContext()) == 1) {
//                LiveHomeItemHolder holder = (LiveHomeItemHolder) recyclerView.getChildViewHolder(view);
//                holder.playVideo();
////                initPlayer(holder.getVideoPlayer());
//            }
//            View lastView = manager.findViewByPosition(lastIndex);
//            if (null != lastView && recyclerView.getChildViewHolder(lastView) instanceof LiveHomeItemHolder) {
//                LiveHomeItemHolder lastHolder = (LiveHomeItemHolder) recyclerView.getChildViewHolder(lastView);
//                lastHolder.pauseVideo();
//
//            }
//        }
//    }


    /**
     * 初始化播放器，让播放器可以全屏
     */
    public void initPlayer(BasePlayerView player) {
        if (null != player) {
            initVideoPlayer(player);
        }
    }

    @Override
    public void onPause() {
        super.onPause();
        RecyclerView.LayoutManager manager = recyclerView.getLayoutManager();
        View lastView = manager.findViewByPosition(lastPlayIndex);
        if (null != lastView && recyclerView.getChildViewHolder(lastView) instanceof LiveHomeItemHolder) {
            LiveHomeItemHolder lastHolder = (LiveHomeItemHolder) recyclerView.getChildViewHolder(lastView);
            lastHolder.pauseVideo();
        }
    }

    @Override
    protected boolean onFragmentShow(boolean isFirst, boolean isCallFromResume) {
        if (isFirst) {
            refreshLayout.autoRefresh();
        }
        return super.onFragmentShow(isFirst, isCallFromResume);
    }

    @Override
    public void onLoadMore() {
        refreshLayout.loadMoreComplete();
    }

    @Override
    public void onRefresh() {
        advanceList.clear();
        getChannels();
    }

    /**
     * 请求基础的路径数据
     */
    private void getChannels() {
        NetUtils.getNetAdapter().getChannelArray(getOwnerName(), channelUrl, new AbsListNetCallback<FocusColumn>(ListTypeUtils.FocusColums()) {
            boolean canComplete = true;

            @Override
            public void onSuc(List<FocusColumn> focusColumns) {
                appiontColumn = null;
                livingColumn = null;
                reviewColumn = null;
                if (ListUtils.isListValued(focusColumns)) {
                    appiontColumn = getChannelColumn(focusColumns, Constances.LIVE_TYPE_APPOINT);
                    livingColumn = getChannelColumn(focusColumns, Constances.LIVE_TYPE_LIVING);
                    reviewColumn = getChannelColumn(focusColumns, Constances.LIVE_TYPE_REVIEW);
                }
                if (liveListGetHelper == null) {
                    liveListGetHelper = new LiveListGetHelper(LiveFragment.this, getString(R.string.livinging_ing)
                            , getString(R.string.live_retrospect));
                }
                liveListGetHelper.setLiving(livingColumn);
                liveListGetHelper.setRetrospect(reviewColumn);
                if (!getAdvanceData()) {
                    dataAddHelper.removeAdvance();
                } else {
                    canComplete = false;
                }
                if (!getLiveDatas(true)) {
                    groupOrderHelper.removeOne();
                    dataAddHelper.removeLiveDatas();
                } else {
                    canComplete = false;
                }
            }

            @Override
            public void onEnd() {
                super.onEnd();
                if (canComplete) {
                    refreshLayout.refreshComplete();
                }
            }
        });
    }

    /**
     * 获取直播预约数据
     *
     * @return
     */
    private boolean getAdvanceData() {
        if (appiontColumn == null) {
            return false;
        }
        groupOrderHelper.addOne();
        ColumnBaseFragment.setSubscribeUrl(appiontColumn.getChannelUrl());
        SharedPreferencesUtil.setParam(getContext(), Constances.SUBSCRIBE_KEY, appiontColumn.getChannelUrl());
        NetUtils.getNetAdapter().getSubscribeListPage(getOwnerName(), appiontColumn.getChannelUrl(), 0, new AbsListNetCallback<FSubscribe>(null) {
            @Override
            public void onSuc(List<FSubscribe> lives) {
                JLog.e("lives==\n" + lives);
                if (ListUtils.isListValued(lives)) {
                    for (int i = 0; i < lives.size(); i++) {
                        long timeInMillis = ServerTime.getInstance(0).getServerRealTimeMilByEla();
                        // long timeInMillis=Calendar.getInstance().getTimeInMillis();
                        FSubscribe fSubscribe = lives.get(i);
                        if (fSubscribe != null) {
                            if (!TextUtils.isEmpty(fSubscribe.getLiveTime())) {
                                Date dataDate = DateUtils.getDataDate(fSubscribe);
                                if (dataDate != null) {
                                    long liveTime = dataDate.getTime();
                                    if (timeInMillis > liveTime) {
                                        lives.remove(i);
                                        i--;
                                        continue;
                                    }
                                }
                            } else {
                                lives.remove(i);
                                i--;
                                continue;
                            }
                        }
                    }
                    if (ListUtils.isListValued(lives)) {
//                        LiveHomeAdvance banner = new LiveHomeAdvance();
//                        banner.setViewType(LiveHomeAdapter.VIEWTYPE_ADVANCE_BANNER);
//                        banner.setList(lives);
//                        setListDatas(null, null, banner, false);

                        LiveHomeAdvance lha = new LiveHomeAdvance();
                        lha.setViewType(LiveHomeAdapter.VIEWTYPE_ADVANCE);
                        lha.setList(lives);
                        setListDatas(null, lha, null, false);
//

//                        List<LiveItem> newsItems = new ArrayList<>();
//                        LiveItem item;
//                        FSubscribe fs;
//                        for (int i = 0; i < lives.size(); i++) {
//                            item = new LiveItem();
//                            fs = lives.get(i);
//                            item.setLiveId(fs.getLiveId());
//                            item.setLiveUrl(fs.getLiveUrl());
//                            item.setLiveTime(fs.getLiveTime());
//                            item.setTitle(fs.getLiveTitle());
//                            item.setLiveImg(fs.getLiveImage());
//                            item.setViewType(LiveHomeAdapter.VIEWTYPE_ADVANCE_LIST);
////                            item.setChannelName(fs.getL);
//                            item.setLiveSource(fs.getLiveSource());
//                            newsItems.add(item);
//                        }
//                        advanceList.addAll(newsItems);
//                        setListDatas(list, null, false);
                    }
                }
            }

            @Override
            public void onEnd() {
                super.onEnd();
                onNetFinish();
            }
        });
        return true;
    }

    /**
     * 调用管理类中方法：依次请求直播、直播回顾数据
     *
     * @param isReset
     * @return
     */
    private boolean getLiveDatas(boolean isReset) {
        groupOrderHelper.addOne();
        boolean b = liveListGetHelper.getLiveList(100, isReset, new AbsListNetCallback<IListShowData>(null, isReset, 0) {
            @Override
            public void onSuc(List<IListShowData> iListShowDatas) {
                setListDatas(iListShowDatas, null, null, (boolean) obj);
            }

            @Override
            public void onEnd() {
                super.onEnd();
                onNetFinish();
            }
        }) >= 0;
        return b;
    }

    private synchronized void setListDatas(List<IListShowData> list, IListShowData
            advance, IListShowData banner, boolean isReset) {
        ArrayList<Pair<String, String>> pairs = new ArrayList<>();
        pairs.add(new Pair<>("页面", "首页"));
        pairs.add(new Pair<>("栏目", "直播"));
//        if (null != list) {
//            //加入预约直播的数据
//            list.addAll(0, advanceList);
//        }
        if (banner != null) {
            dataAddHelper.setAdvanceBannerData(getContext(), banner, pairs);
        } else if (advance != null) {
            dataAddHelper.setAdvanceData(getContext(), advance, pairs);
        } else {
            if (ListUtils.isListValued(list)) {
                dataAddHelper.addOrLiveDatas(getContext(), list, isReset, pairs);
            } else {
                if (isReset) {
                    dataAddHelper.removeLiveDatas();
                }
            }
        }
        if (adapter == null) {
            adapter = dataAddHelper.getAdapter(getContext());
            adapter.setOnItemSubscribeClick(onItemSubscribeClick);
            recyclerView.setAdapter(adapter);
            adapter.setListener(this);
            adapter.setCanSelector(true);
        }
    }

    /**
     * @param list
     * @param rePos 当前回顾的pos
     * @return 回顾的title的pos
     */
    private int parseListData(List<IListShowData> re, List<LiveItem> list,
                              int livingTitlePos, int rePos) {
        if (!ListUtils.isListValued(list)) {
            return -1;
        }
        int i = 0;
        LiveItem li = list.get(0);
        if (livingTitlePos < 0 && li.isLiving()) {
            Titles t = new Titles();
            t.setTitle(getString(R.string.livinging));
            t.setViewType(LiveHomeAdapter.VIEWTYPE_TITLE);
            re.add(t);
        }
        li.setViewType(LiveHomeAdapter.VIEWTYPE_LIVE);
        re.add(li);
        i++;
        for (; i < list.size(); i++) {
            li = list.get(i);
            if (rePos < 0) {
                if (!list.get(i).isLiving()) {
                    Titles t = new Titles();
                    t.setTitle(getString(R.string.retrospect));
                    t.setViewType(LiveHomeAdapter.VIEWTYPE_TITLE);
                    re.add(t);
                    rePos = i;
                }
            }
            li.setViewType(LiveHomeAdapter.VIEWTYPE_LIVE);
            re.add(li);
        }
        return rePos;
    }

    private FocusColumn getChannelColumn(List<FocusColumn> list, int type) {
        if (ListUtils.isListValued(list)) {
            for (int i = 0; i < list.size(); i++) {
                FocusColumn fc = list.get(i);
                if (fc == null) {
                    list.remove(fc);
                    i--;
                } else {
                    if (fc.getSubChannelType() == type) {
                        list.remove(i);
                        return fc;
                    }
                }
            }
        }
        return null;
    }

    private synchronized void onNetFinish() {
        if (groupOrderHelper.removeOne()) {
            refreshLayout.refreshComplete();
        }
    }

    private List<FSubscribe> getTestAdvanceDatq() {
        String[] strs = getResources().getStringArray(R.array.titlesss);
        int l = strs.length;
        int s = (int) (1 + Math.random() * l);
        ArrayList<FSubscribe> list = new ArrayList<>();
        for (int i = 0; i < s; i++) {
            FSubscribe fs = new FSubscribe();
            fs.setLiveTitle(i + strs[(int) (Math.random() * l)]);
            list.add(fs);
        }
        return list;
    }

    private List<LiveItem> getTestLiveData() {
        String[] strs = getResources().getStringArray(R.array.titlesss);
        int l = strs.length;
        int s = (int) (1 + Math.random() * 4);
        ArrayList<LiveItem> list = new ArrayList<>();
        long t = System.currentTimeMillis();
        for (int i = 0; i < s; i++) {
            LiveItem li = new LiveItem();
            li.setTitle(strs[(int) (Math.random() * l)]);
            li.setDataDate(new Date(s));
            s = (int) (s - i * 60000 - Math.random() * 600000);
            li.setChannelName(i + "资讯");
            li.setLiving(true);
            list.add(li);
        }
        s = (int) (1 + Math.random() * 10);
        for (int i = 0; i < s; i++) {
            LiveItem li = new LiveItem();
            li.setTitle(strs[(int) (Math.random() * l)]);
            li.setDataDate(new Date(s));
            s = (int) (s - i * 60000 - Math.random() * 600000);
            li.setChannelName(i + "资讯");
            list.add(li);
        }
        return list;
    }

    OnItemInternalClick onItemSubscribeClick = new OnItemInternalClick() {
        @Override
        public void onItemInternalClick(View itemView, View view, int position) {
            Intent intent = new Intent(getContext(), MySubscribeActivity.class);
            if (appiontColumn != null) {
                if (!TextUtils.isEmpty(appiontColumn.getChannelUrl()) && appiontColumn.getChannelUrl().endsWith(".json")) {
                    intent.putExtra(BaseActivity.EX_TYPE, types);
                    intent.putExtra(BaseActivity.EX_URL, appiontColumn.getChannelUrl());
                    startActivity(intent);
                } else {
                    Toast.makeText(getContext(), "url错误", Toast.LENGTH_SHORT).show();
                }
            }

        }
    };

    private boolean isNotScrolled = false;
    private boolean isNotScrollStateChanged = false;

    @Override
    public void OnItemInit(BasePlayerView player, int position) {
        initPlayer(player);
    }

    @Override
    public void OnItemClick(LiveItem item, int position) {
        if (lastPlayIndex == position) {
            RecyclerView.LayoutManager manager = recyclerView.getLayoutManager();
            View lastView = manager.findViewByPosition(lastPlayIndex);
            if (null != lastView && recyclerView.getChildViewHolder(lastView) instanceof LiveHomeItemHolder) {
                LiveHomeItemHolder lastHolder = (LiveHomeItemHolder) recyclerView.getChildViewHolder(lastView);
                lastHolder.exchangeStatus();
            }
            return;
        }
        JLog.e("OnItemClick", " position = " + position);
        isNotScrolled = true;
        isNotScrollStateChanged = true;
        RecyclerView.LayoutManager manager = recyclerView.getLayoutManager();
        View lastView = manager.findViewByPosition(lastPlayIndex);
        if (null != lastView && recyclerView.getChildViewHolder(lastView) instanceof LiveHomeItemHolder) {
            LiveHomeItemHolder lastHolder = (LiveHomeItemHolder) recyclerView.getChildViewHolder(lastView);
            lastHolder.pauseVideo();
        }
        if (position < adapter.getItemCount()) {
            if (position != -1) {
                smoothMoveToPosition(recyclerView, position);
            } else {
                smoothMoveToPosition(recyclerView, position + 1);
            }
        }
//        recyclerView.scrollToPosition(position);

        View view = manager.findViewByPosition(position);

        if ( null != view && recyclerView.getChildViewHolder(view) instanceof LiveHomeItemHolder) {
            LiveHomeItemHolder lastHolder = (LiveHomeItemHolder) recyclerView.getChildViewHolder(view);
            willHolder = lastHolder;
            index = position;
            if(checkNet()) {
                String liveID = lastHolder.playVideo();
//            initPlayer(lastHolder.getVideoPlayer());
                lastPlayIndex = position;
                if (!TextUtils.isEmpty(liveID)) {
                    //播放，增加点击量
                    initViewClickData(liveID);
                }
            }
        }
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                isNotScrolled = false;
                isNotScrollStateChanged = false;
            }
        }, 500);
    }
    /**
     * 增加直播点击
     *
     * @param liveID
     */
    private void initViewClickData(final String liveID) {
        ArrayMap<String, Object> p = new ArrayMap<>();
        p.put("id", liveID);
        p.put("type", 1);//type（0.新闻 1.直播)
        NetUtils.getNetAdapter().addNewOrLivingClick(getOwnerName(), p, new AbsNetCallBack<SingleResult>(SingleResult.class) {
            @Override
            public void onSuc(SingleResult vo) {
                JLog.e("initViewClickData", "GreatestFragment liveID = "+liveID + vo.isSuccess());
            }

            @Override
            public void onEnd() {
                super.onEnd();
            }

            @Override
            public void onError(Throwable ex, String errorMsg) {
                super.onError(ex, errorMsg);
            }
        });


    }
    //记录当前准备播放的数据
    private LiveHomeItemHolder willHolder;
    private int index;

    private boolean checkNet() {
        if (!Cache.getInstance().isCheckNet() && 1 != NetModeUtil.GetNetype(getContext())) {
            showNetDialog();
        } else {
            return true;
        }
        return false;
    }
    protected void showNetDialog() {
        if(Cache.getInstance().isCheckNet()){
            if(null!=willHolder) {
                String liveID =   willHolder.playVideo();
                lastPlayIndex = index;
                if (!TextUtils.isEmpty(liveID)) {
                    //播放，增加点击量
                    initViewClickData(liveID);
                }
            }
            return;
        }
        if (netModeDiaFragment == null) {
            netModeDiaFragment = new NetModeDiaFragment();
        }
        if(!netModeDiaFragment.isAdded()) {
            netModeDiaFragment.setCallBack(netCallBack);
            netModeDiaFragment.show(getFragmentManager(), NET_TAG);
        }
    }

    BaseDialogFragment.ICallBack netCallBack = new BaseDialogFragment.ICallBack() {
        @Override
        public void onCallBackMsg(BaseDialogFragment fragment, Message msg) {
            if (msg.what == NetModeDiaFragment.NO_TAG) {
//                floatVideoUtils.stopVideoView();
            } else if (msg.what == NetModeDiaFragment.OK_TAG) {
                Cache.getInstance().setCheckNet(true);
                if(null!=willHolder) {
                    String liveID =  willHolder.playVideo();
                    lastPlayIndex = index;

                    if (!TextUtils.isEmpty(liveID)) {
                        //播放，增加点击量
                        initViewClickData(liveID);
                    }
                }
            }
        }
    };

    //目标项是否在最后一个可见项之后
    private boolean mShouldScroll;
    //记录目标项位置
    private int mToPosition;

    /**
     * 滑动到指定位置
     */
    private void smoothMoveToPosition(RecyclerView mRecyclerView, final int position) {
        JLog.e("OnItemClick---", "smoothMoveToPosition  position = " + position);
        // 第一个可见位置
        int firstItem = mRecyclerView.getChildLayoutPosition(mRecyclerView.getChildAt(0));
        // 最后一个可见位置
        int lastItem = mRecyclerView.getChildLayoutPosition(mRecyclerView.getChildAt(mRecyclerView.getChildCount() - 1));
        if (position < firstItem) {
            // 第一种可能:跳转位置在第一个可见位置之前
            mRecyclerView.smoothScrollToPosition(position);
        } else if (position <= lastItem) {
            // 第二种可能:跳转位置在第一个可见位置之后
            int movePosition = position - firstItem;
            if (movePosition >= 0 && movePosition < mRecyclerView.getChildCount()) {
                int top = mRecyclerView.getChildAt(movePosition).getTop();
                mRecyclerView.smoothScrollBy(0, top);
            }
        } else {
            // 第三种可能:跳转位置在最后可见项之后
            mRecyclerView.smoothScrollToPosition(position);
            mToPosition = position;
            mShouldScroll = true;
        }
    }
}
